import 'package:enterprise_v6_app/app/components/custom_modele/custom_gradient_line.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_table.dart';
import 'package:enterprise_v6_app/app/components/special_operation/custom_title_chart_page.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/modules/application/intelligent_inspection_page/inspec_all_view_page/inspec_all_view_controller.dart';
import 'package:syncfusion_flutter_charts/charts.dart' as charts;
import 'package:syncfusion_flutter_gauges/gauges.dart';

/// 巡检总览
class InspecAllViewPage extends StatelessWidget {
  InspecAllViewPage({super.key});

  final controller = Get.put(InspecAllViewController());

  /// 巡检任务子项
  Widget _buildTaskItemBar({
    required String title,
    required int value,
    required int total,
    required Color color,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          height: 90.w,
          width: 90.w,
          child: SfRadialGauge(
            axes: <RadialAxis>[
              RadialAxis(
                  radiusFactor: 0.85,
                  axisLineStyle: AxisLineStyle(color: const Color(0xFFE0E4EB).withOpacity(0.8), thickness: 0.24, thicknessUnit: GaugeSizeUnit.factor),
                  showLabels: false,
                  showTicks: false,
                  startAngle: 270,
                  endAngle: 270,
                  pointers: <GaugePointer>[
                    RangePointer(
                        pointerOffset: 0.05,
                        width: 0.15,
                        value: value != 0 ? (value / total) * 100 : 0,
                        cornerStyle: CornerStyle.bothCurve,
                        color: color,
                        sizeUnit: GaugeSizeUnit.factor,
                    ),
                  ],
                  annotations: <GaugeAnnotation>[
                    GaugeAnnotation(
                        widget: Text(
                           value != 0 && total != 0 ? '${((value/total) * 100).toInt()}%' : '0%',
                          style: TextStyle(color: color, fontWeight: FontWeight.w400, fontSize: 16.sp),
                        ),
                        positionFactor: 0.15,
                        angle: 90)
                  ])
            ],
          ),
        ),
        AppGaps.vGap4,
        Text(
          '$title:$value',
          style: TextStyle(
            color: const Color(0xFFA0A7B5),
            fontWeight: FontWeight.w400,
            fontSize: 12.sp,
          ),
        ),
      ],
    );
  }

  /// 巡检计划
  Widget _insProject() {
    return CustomTitleChartPage(
      title: '巡检计划',
      child: SizedBox(
        height: 130.w,
        child: Column(
          children: [
            SizedBox(
              height: 120.w,
              child: charts.SfCircularChart(
                legend: charts.Legend(
                  isVisible: true,
                  position: charts.LegendPosition.right,
                  overflowMode: charts.LegendItemOverflowMode.none,
                  legendItemBuilder: (String name, dynamic series, dynamic point, int seriesIndex) {
                    return Container(
                      width: 110.w,
                      height: 22.w,
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 5.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Container(
                                width: 10.w,
                                height: 10.w,
                                padding: EdgeInsets.all(2.w),
                                margin: EdgeInsets.only(right: 2.w),
                                decoration: BoxDecoration(
                                  color: controller.questionData[seriesIndex].color,
                                  borderRadius: BorderRadius.circular(5.w),
                                ),
                                child: Container(
                                  decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.w)),
                                ),
                              ),
                              Text(
                                name,
                                style: TextStyle(fontSize: 12.w, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                              ),
                            ],
                          ),
                          Text(
                            '${controller.questionData[seriesIndex].y.toInt()}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: controller.questionData[seriesIndex].color,
                            ),
                          ),
                          Text(
                            '${((controller.questionData[seriesIndex].y / (controller.planTotal == 0 ? 1 : controller.planTotal)) * 100).toInt()}%',
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: controller.questionData[seriesIndex].color,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  toggleSeriesVisibility: false,
                ),
                annotations: [
                  charts.CircularChartAnnotation(
                    widget: Container(
                      width: 50.w,
                      height: 50.w,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(50.w),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '巡检计划',
                            style: TextStyle(
                              fontSize: 10.w,
                              fontWeight: FontWeight.w400,
                              color: const Color(0xffA0A7B5),
                            ),
                          ),
                          Text(
                            '${controller.planTotal}',
                            style: TextStyle(fontSize: 14.w, fontWeight: FontWeight.w400, color: const Color(0xFF495061)),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
                series: <charts.CircularSeries>[
                  charts.DoughnutSeries<ChartData, String>(
                    dataSource: controller.questionData,
                    pointColorMapper: (ChartData data, _) => data.color,
                    xValueMapper: (ChartData data, _) => data.x,
                    yValueMapper: (ChartData data, _) => data.y,
                    name: '园区资料文件',
                    dataLabelSettings: const charts.DataLabelSettings(
                      isVisible: false,
                      labelPosition: charts.ChartDataLabelPosition.inside,
                    ),
                    radius: '100%',
                    innerRadius: '65%',
                    enableTooltip: true,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 巡检任务
  Widget _insTask() {
    return CustomTitleChartPage(
      title: '巡检任务',
      titleRightWidget: Text('${controller.inspecTaskEntity.taskTotalNum}',style: TextStyle(
        color: AppColors.font_color_blue,
        fontSize: 16.sp,
        fontWeight: FontWeight.bold,
      ),),
      child: SizedBox(
        height: 240.w,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildTaskItemBar(
                  title: '已完成',
                  value: controller.inspecTaskEntity.quantityCompleted ?? 0,
                  total: controller.inspecTaskEntity.taskTotalNum ?? 0,
                  color: const Color(0xff33a9ff),
                ),
                _buildTaskItemBar(
                  title: '待巡检',
                  value: controller.inspecTaskEntity.toBeCompleted ?? 0,
                  total: controller.inspecTaskEntity.taskTotalNum ?? 0,
                  color: const Color(0xfffc9900),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildTaskItemBar(
                  title: '逾期补检',
                  value: controller.inspecTaskEntity.reExaminationNum ?? 0,
                  total: controller.inspecTaskEntity.taskTotalNum ?? 0,
                  color: const Color(0xFFFFCE24),
                ),
                _buildTaskItemBar(
                  title: '漏检',
                  value: controller.inspecTaskEntity.missingNum ?? 0,
                  total: controller.inspecTaskEntity.taskTotalNum ?? 0,
                  color: const Color(0xFFFD6B6B),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 报警
  Widget _alarm() {
    return CustomTitleChartPage(
      title: '报警',
      child: SizedBox(
        height: 630.w,
        child: Column(
          children: [
            _buildAlarmSummary(),
            Container(
              height: 140.w,
              margin: EdgeInsets.only(right: 55.w),
              child: charts.SfPyramidChart(
                legend: charts.Legend(
                  isVisible: false,
                  position: charts.LegendPosition.right,
                  overflowMode: charts.LegendItemOverflowMode.wrap,
                  legendItemBuilder: (String name, dynamic series, dynamic point, int seriesIndex) {
                    return Container(
                      width: 60.w,
                      height: 25.w,
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 5.w),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            name,
                            style: TextStyle(fontSize: 12.w, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                          ),
                          Text(
                            '${controller.initRiskData[seriesIndex].y.toInt()}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: controller.initRiskData[seriesIndex].color,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
                series: charts.PyramidSeries<ChartData, String>(
                  gapRatio: 0.08,
                  dataSource: controller.initRiskData,
                  xValueMapper: (ChartData data, _) => data.x,
                  yValueMapper: (ChartData data, _) => data.y,
                  dataLabelSettings: const charts.DataLabelSettings(
                    isVisible: true,
                    labelPosition: charts.ChartDataLabelPosition.outside,
                  ),
                  //  演示设置数据为0
                  textFieldMapper: (datum, index) => '${datum.x}：${datum.y - 1}次',
                ),
              ),
            ),
            AppGaps.vGap10,
            _buildChartExplain(),
            AppGaps.vGap16,
            _buildHistory(),
          ],
        ),
      ),
    );
  }

  /// 消警 图表 解释
  Widget _buildChartExplain() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFF7F7FD),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: controller.initRiskData.map((e) => _buildChartExplainItem(e.x, e.y.toString(), e.color)).toList(),
      ),
    );
  }

  /// 消警 图表 解释 单个
  Widget _buildChartExplainItem(String title,String? content,Color? color) {
    return ListTile(
      title: Row(
        children: [
          Container(
            height: 8.w,
            width: 24.w,
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(5.w),
            ),
          ),
          AppGaps.hGap10,
          Text(
            title,
            style: TextStyle(color: const Color(0xFF495061), fontWeight: FontWeight.w500, fontSize: 12.w),
          ),
        ],
      ),
      subtitle: Text(
        '未处理0条，消警0条，超时0条，误报0条',
        style: TextStyle(
          color: const Color(0xFF8393AC),
          fontSize: 12.w,
        ),
      ),
    );
  }

  /// 消警 总览
  Widget _buildAlarmSummary() {
    return Container(
      decoration: BoxDecoration(color: const Color(0x1A5C6DFF), borderRadius: BorderRadius.all(Radius.circular(8.w))),
      child: Padding(
        padding: EdgeInsets.all(10.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildCancelAlarmSummaryTop('未处理', '0'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('消警', '0'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('超时', '0'),
            CustomVerticalGradientLine(height: 24.w),
            _buildCancelAlarmSummaryTop('误报', '0'),
          ],
        ),
      ),
    );
  }

  /// 消警 总览 顶部 单个
  Widget _buildCancelAlarmSummaryTop(String title,String? value) {
    const color = Color.fromARGB(255, 102, 116, 245);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          value ?? '空',
          style: const TextStyle(
            color: color,
            fontWeight: FontWeight.w500,
          ),
        ),
        Text(
          title,
          style: const TextStyle(
            color: color,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 消警 历史
  Widget _buildHistory() {
    return CustomTable(
      xLen: controller.test.length,
      yLen: 3,
      alignment: Alignment.center,
      cellPadding: EdgeInsets.all(6.w),
      cellBuilder: (x, y) {
        return Text(
          '0',
          style: TextStyle(
            color: const Color(0xFF818499),
            fontSize: 12.w,
          ),
        );
      },
      headBuilder: (x) => Text(
        controller.test[x],
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 12.w,
        ),
      ),
    );
  }

  /// 部门巡检
  Widget _departmentInspection() {
    return CustomTitleChartPage(
      title: '部门巡检',
      child: SizedBox(
              height: 350.w,
              child: charts.SfCartesianChart(
                  legend: const charts.Legend(
                    isVisible: true,
                    position: charts.LegendPosition.bottom,
                    overflowMode: charts.LegendItemOverflowMode.wrap,
                  ),
                  // 设置x轴文字宽度
                  primaryXAxis: charts.CategoryAxis(
                    // 设置x轴文字宽度
                    majorGridLines: const charts.MajorGridLines(
                      width: 0,
                    ),
                    // 设置边框为虚线
                    axisLine: const charts.AxisLine(
                      dashArray: <double>[3, 3],
                    ),
                    majorTickLines: const charts.MajorTickLines(
                      width: 0,
                    ),
                  ),
                  primaryYAxis: charts.NumericAxis(
                    majorGridLines: const charts.MajorGridLines(
                      dashArray: <double>[3, 3],
                    ),
                    axisLine: const charts.AxisLine(
                      dashArray: <double>[3, 3],
                    ),
                    majorTickLines: const charts.MajorTickLines(
                      width: 0,
                    ),
                  ),
                  plotAreaBorderWidth: 0,
                  //跟踪球
                  trackballBehavior: charts.TrackballBehavior(
                    //纵向选择指示器
                    activationMode: charts.ActivationMode.singleTap,
                    enable: true,
                    tooltipAlignment: charts.ChartAlignment.center,
                    // 线的颜色
                    lineColor: const Color(0xff6DDF9A),
                    //工具提示位置(顶部)
                    //跟踪球始终显示(纵向选择指示器)
                    tooltipDisplayMode: charts.TrackballDisplayMode.groupAllPoints,
                  ),
                  series: controller.lineData
              ),
            ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColors.bg_color_grey,
      padding: EdgeInsets.only(
        left: 14.w,
        right: 14.w,
        top: 16.w,
      ),
      child: SingleChildScrollView(
        child: Column(
          children: [
            GetBuilder(
              init: controller,
              id: 'plan',
              builder: (_) {
                return _insProject();
              },
            ),
            AppGaps.vGap16,
            GetBuilder(
              init: controller,
              id: 'task',
              builder: (_) {
                return _insTask();
              },
            ),
            AppGaps.vGap16,
            GetBuilder(
              init: controller,
              id: 'alarm',
              builder: (_) {
                return _alarm();
              },
            ),
            AppGaps.vGap16,
            GetBuilder(
              init: controller,
              id: 'department',
              builder: (_) {
                return _departmentInspection();
              },
            ),
            AppGaps.vGap16,
          ],
        ),
      ),
    );
  }
}
